package com.wjx.reservation_service.controller;

import com.wjx.reservation_service.model.Appointment;
import com.wjx.reservation_service.model.Rating;
import com.wjx.reservation_service.model.Serve;
import com.wjx.reservation_service.model.User;
import com.wjx.reservation_service.service.impl.IAppointmentServiceImpl;
import com.wjx.reservation_service.service.impl.IRatingServiceImpl;
import com.wjx.reservation_service.service.impl.IServeServiceImpl;
import com.wjx.reservation_service.service.impl.IUserServiceImpl;
import com.wjx.reservation_service.tool.Tool;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class UserController {
    @Autowired
    private IUserServiceImpl userService;
    @Autowired
    private IServeServiceImpl serveService;
    @Autowired
    private IRatingServiceImpl ratingService;
    @Autowired
    private IAppointmentServiceImpl appointmentService;
    @Autowired
    private Tool tool;

    @GetMapping("/toLogin")
    public String toLogin() {
        return "user/login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model,
                        HttpServletResponse response, HttpSession session)
            throws Exception {
        User user = userService.selectUserByUsername(username);
        if (user != null) {
            if (user.getPassword() != null && Objects.equals(user.getPassword(), password)) {
                session.setAttribute("user", user);
                if (user.getAuthority().equals("普通用户")) {
                    model.addAttribute("choice", 0);
                    return "user/index";
                }
                if (user.getAuthority().equals("管理员") ) {
                    model.addAttribute("index", 1);
                    return "admin/index";
                }

            }
        }
        response.getWriter().write("<script>alert('用户名或密码错误！')</script>");
        return "user/login";

    }
    @GetMapping("/quit")
    public String quit(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/toLogin";
    }
    @GetMapping("/toRegister")
    public String toRegister() {
        return "user/register";
    }

    @PostMapping("/register")
    public String register(String username, String password, HttpServletResponse response) throws Exception {

        if (Objects.equals(username, "") || Objects.equals(password, "")) {
            response.getWriter().write("<script>alert('用户名和密码都不能为空！')</script>");
            return "user/register";
        }
        User user = userService.selectUserByUsername(username);
        if (user != null && user.getUsername() != null && user.getUsername().equals(username)) {
            response.getWriter().write("<script>alert('用户名已存在！')</script>");
            return "user/register";
        }
        if (userService.register(username, password,"普通用户") >= 1) {
            response.getWriter().write("<script>alert('注册成功，前往登录页面')</script>");
            return "user/login";
        } else {
            response.getWriter().write("<script>alert('注册失败')</script>");
            return "user/register";
        }
    }

    @GetMapping("/user/index")
    public String index(Model model) {
        model.addAttribute("choice", 0);
        return "user/index";
    }

    @GetMapping("/service-center")
    public String service_center(Model model) {
        model.addAttribute("serveList", serveService.showService());
        model.addAttribute("choice", 1);
        return "user/index";
    }

    @PostMapping("/search")
    public String search(String keyword, Model model) {
        model.addAttribute("serveList", serveService.search(keyword));
        model.addAttribute("choice", 1);
        return "user/index";
    }

    @GetMapping("/service-detail")
    public String service_detail(int id, int editId, @RequestParam(name = "afterEditRating", defaultValue = "0")
    int afterEditRating, Model model) {
        model.addAttribute("choice", 2);
        model.addAttribute("appointment", 0);
        model.addAttribute("editId", editId);
        model.addAttribute("afterEditRating", afterEditRating);
        model.addAttribute("serve", serveService.queryServiceById(id));
        List<Rating> ratingList = ratingService.queryRatingByServiceId(id);
        model.addAttribute("ratingList", ratingList);
        List<User> userList = new ArrayList<>();
        for (Rating rating : ratingList) {
            userList.add(userService.queryUserById(rating.getUserId()));
        }
        model.addAttribute("userList", userList);
        return "user/index";
    }

    @GetMapping("/toAppointment")
    public String appointment(int serviceId, Model model) {
        model.addAttribute("choice", 2);
        model.addAttribute("appointment", 1);
        model.addAttribute("service", serveService.queryServiceById(serviceId));
        return "user/index";
    }

    @PostMapping("/addAppointment")
    public void addAppointment(Appointment appointment, Model model,
                               HttpServletResponse response) throws Exception {

        appointment.setStatus("预约中");
        appointment.setCreatedTime(tool.currentTime());
        appointment.setLastUpdatedTime(tool.currentTime());
        int temp = appointmentService.addAppointment(appointment);
        if (temp >= 1) {
            model.addAttribute("choice", 3);
            response.getWriter().write("<script>alert('预约中，请耐心等待，前往我的预约查看预约详情！')</script>");
            response.getWriter().write("<script>window.location.href='/myAppointment'</script>");
        } else {
            response.getWriter().write("<script>alert('预约失败，返回预约服务中心！')</script>");
            response.getWriter().write("<script>window.location.href='/service-center'</script>");
        }
    }

    @GetMapping("/myAppointment")
    public String myAppointment(Model model, HttpSession session, HttpServletResponse response) throws Exception {
        if (session != null && session.getAttribute("user") != null) {
            User user = (User) session.getAttribute("user");
            List<Appointment> appointmentList = appointmentService.queryAppointmentByUserId(user.getId());
            model.addAttribute("appointmentList", appointmentList);
            List<Serve> serveList = new ArrayList<>();
            for (Appointment appointment : appointmentList) {
                serveList.add(serveService.queryServiceById(appointment.getServiceId()));
            }
            model.addAttribute("serveList", serveList);
            model.addAttribute("choice", 3);
            return "user/index";
        } else {
            response.getWriter().write("<script>alert('没有登录，请先登录才能查看我的预约订单。')</script>");
            return "user/login";
        }

    }

    @PostMapping("/userEditRating")
    public void userEditRating(int id, int score, String feedback, Model model, HttpServletResponse response) throws Exception {
        int temp = ratingService.updateScoreById(id, score, feedback,new Tool().currentTime());
        Rating rating = ratingService.queryRatingById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('编辑成功！')</script>");
            response.getWriter().write("<script>window.location.href='/service-detail?id="
                    + rating.getServiceId() + "&editId=" + id + "&afterEditRating=1'</script>");
        } else {
            response.getWriter().write("<script>alert('编辑失败！')</script>");
            response.getWriter().write("<script>window.location.href='/service-detail?id="
                    + rating.getServiceId() + "&editId=0&afterEditRating=0'</script>");
        }
    }

    @GetMapping("/deleteRating")
    public void deleteRating(int id, HttpServletResponse response) throws Exception {
        Rating rating = ratingService.queryRatingById(id);
        int temp = ratingService.deleteRatingById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('删除成功！')</script>");
            response.getWriter().write("<script>window.location.href='/service-detail?id="
                    + rating.getServiceId() + "&editId=0&afterEditRating=0'</script>");
        } else {
            response.getWriter().write("<script>alert('删除失败！')</script>");
            response.getWriter().write("<script>window.location.href='/service-detail?id="
                    + rating.getServiceId() + "&editId=0&afterEditRating=0'</script>");
        }
    }

    @GetMapping("/isAddRating")
    public void toAddRating(int appointmentId, int userId, int serviceId,
                              HttpServletResponse response) throws Exception {
        Rating rating = ratingService.queryRatingByAppointmentId(appointmentId);
        if (rating != null && rating.getFeedback() != null) {
            response.getWriter().write("<script>alert('您已评价，无需重复评价！');" +
                    "window.location.href='/myAppointment'</script>");
        } else {
            response.getWriter().write("<script>window.location.href='/toAddRating?appointmentId=" +
                    appointmentId+"&userId="+userId+"&serviceId="+serviceId+"'</script>");
        }
    }
    @GetMapping("/toAddRating")
    public String toAddRating(int appointmentId, int userId, int serviceId,Model model){
        model.addAttribute("choice", 4);
        model.addAttribute("appointmentId", appointmentId);
        model.addAttribute("userId", userId);
        model.addAttribute("serviceId", serviceId);
        return "user/index";
    }

    @PostMapping("/addRating")
    public void addRating(int appointmentId, int userId, int serviceId,
                            int score, String feedback, HttpServletResponse response) throws Exception {
        Rating rating = new Rating(serviceId, userId, appointmentId, score, feedback,
                new Tool().currentTime(), new Tool().currentTime());
        int temp = ratingService.addRating(rating);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('感谢您的评价！');" +
                    "window.location.href='/myAppointment'</script>");
        }else {
            response.getWriter().write("<script>alert('评价失败！');" +
                    "window.location.href='/myAppointment'</script>");
        }
    }
    @GetMapping("/myInfo")
    public String myInfo(Model model){
        model.addAttribute("myInfo",1);
        return "user/index";
    }
    @PostMapping("/editPassword")
    public void editPassword(User user,HttpServletResponse response,HttpSession session)throws Exception{
        int temp = userService.updateUserById(user);
        if (temp >= 1) {
            session.removeAttribute("user");
            session.setAttribute("user",user);
            response.getWriter().write("<script>alert('密码编辑成功！');" +
                    "window.location.href='/myInfo'</script>");
        }else {
            response.getWriter().write("<script>alert('密码编辑失败！');" +
                    "window.location.href='/myInfo'</script>");
        }
    }
}
